﻿using System.IO;
using System.Collections.Generic;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
using UnityEditorInternal;
#endif

namespace KuiHuaBaoDian.Services.Guide {

    public class GuideSetting : ScriptableObject {

        [SerializeField]
        private bool m_IsEnabled = true;
        public bool IsEnabled => m_IsEnabled;

#if UNITY_EDITOR
        public static GuideSetting Instance {
            get {
                var instance = default(GuideSetting);
                var guids = AssetDatabase.FindAssets($"t:{nameof(GuideSetting)}");
                if (guids.Length > 1) {
                    Debug.LogWarning("存在多个新手引导配制");
                }
                if (guids.Length == 0) {
                    instance = CreateInstance<GuideSetting>();
                    AssetDatabase.CreateAsset(instance, Path.Combine("Assets/AddressablesAssets", $"{nameof(GuideSetting)}.asset"));
                    AssetDatabase.SaveAssets();
                } else {
                    instance = AssetDatabase.LoadAssetAtPath<GuideSetting>(AssetDatabase.GUIDToAssetPath(guids[0]));
                }
                instance.ClearMissingSections();
                return instance;
            }
        }

        public void ClearMissingSections() {
            var so = new SerializedObject(this);
            var sp = so.FindProperty(nameof(SectionList));
            var exsitList = new List<GuideSection>();
            for (var i = 0; i < sp.arraySize; ++i) {
                var item = sp.GetArrayElementAtIndex(i);
                if (item.objectReferenceValue is GuideSection section && !exsitList.Contains(section) && !string.IsNullOrWhiteSpace(AssetDatabase.GetAssetPath(section))) {
                    exsitList.Add(section);
                } else {
                    sp.DeleteArrayElementAtIndex(i--);
                }
            }
            so.ApplyModifiedPropertiesWithoutUndo();
        }

        public AssemblyDefinitionAsset[] AssemblyDefinitionAssets;
        public AssemblyDefinitionAsset[] EditorAssemblyDefinitionAssets;
#endif

        public List<GuideSection> SectionList = new();
    }
}
